﻿#region File and License Information
/*
<File>
	<License>
		Copyright © 2009 - 2017, Daniel Vaughan. All rights reserved.
		This file is part of Calcium (http://calciumsdk.net), 
		which is released under the MIT License.
		See file /Documentation/License.txt for details.
	</License>
	<CreationDate>$CreationDate$</CreationDate>
</File>
*/
#endregion

using System;
using System.IO;

namespace Outcoder.IO
{
	public class FileNameGenerator
	{
		public static string CreateFileNameUsingTime(string fileExtensionWithDot)
		{
			string timePart = DateTime.Now.ToString("yyyy-M-dd--HH-mm-ss");
			string result = timePart + fileExtensionWithDot;
			return result;
		}

		// From http://stackoverflow.com/questions/309485/c-sharp-sanitize-file-name
		public static string MakeValidFileName(string name, bool stripSpaces = true)
		{
			string invalidCharacters = System.Text.RegularExpressions.Regex.Escape(new string(System.IO.Path.GetInvalidFileNameChars()));
			string expression = string.Format(@"([{0}]*\.+$)|([{0}]+)", invalidCharacters);

			var result = System.Text.RegularExpressions.Regex.Replace(name, expression, "_");

			if (stripSpaces)
			{
				result = result.Replace(" ", "");
			}

			return result;
		}

		/// <summary>
		/// Generates a file path that is unique. If a collision occurrs 
		/// an integer is included in the name until the name is unique.
		/// For example MyFile.jpg might become MyFile(1).jpg
		/// If the supplied fullpath is already unique then it is returned.
		/// </summary>
		/// <param name="fullPath">The full file system path to the file.</param>
		/// <returns>For example MyFile.jpg might become MyFile(1).jpg
		/// If the supplied fullpath is already unique then it is returned.</returns>
		public static string GenerateUniqueFileName(string fullPath)
		{
			int count = 1;

			string fileNameOnly = Path.GetFileNameWithoutExtension(fullPath);
			string extension = Path.GetExtension(fullPath);
			string path = Path.GetDirectoryName(fullPath);
			string newFullPath = fullPath;

			while (File.Exists(newFullPath))
			{
				string tempFileName = string.Format("{0}({1})", fileNameOnly, count++);
				newFullPath = Path.Combine(path, tempFileName + extension);
			}

			return newFullPath;
		}
	}
}
